<template>
  <div>
    <el-switch
      v-model="draggable"
      active-text="开启拖拽"
      inactive-text="关闭拖拽"
    ></el-switch>
    <el-button v-if="draggable" @click="batchSave">批量保存</el-button>
    <el-button type="danger" @click="batchDelete">批量删除</el-button>
    <el-button @click="appendRoot">增加大分类</el-button>
    <el-tree
      :data="menus"
      :props="defaultProps"
      :expand-on-click-node="false"
      show-checkbox
      node-key="id"
      :default-expanded-keys="expandedKey"
      :draggable="draggable"
      :allow-drop="allowDrop"
      @node-drop="handleDrop"
      ref="menuTree"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="node.level <= 2"
            type="text"
            size="mini"
            @click="() => append(data)"
            >添加</el-button
          >
          <el-button type="text" size="mini" @click="edit(data)"
            >编辑</el-button
          >
          <el-button
            v-if="node.childNodes.length == 0"
            type="text"
            size="mini"
            @click="() => remove(node, data)"
            >删除</el-button
          >
        </span>
      </span>
    </el-tree>
    <el-dialog
      :title="title"
      :visible.sync="addRootVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input
            v-model="category.categoryName"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRootVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitData">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input
            v-model="category.categoryName"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitData">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  props: {},
  data() {
    return {
      pCid: [],
      draggable: false,
      addRootVisible: false,
      excludeId: -1,
      updateNodes: [],
      maxLevel: 0,
      title: "",
      dialogType: "", //edit,add
      category: {
        id: 0,
        categoryName: "",
        parentId: 0,
        categoryLevel: 0,
        sort: 0,
        createTime: "",
        updateTime: "",
      },
      dialogVisible: false,
      menus: [],
      expandedKey: [],
      defaultProps: {
        children: "children",
        label: "categoryName",
      },
    };
  },

  //计算属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    getMenus() {
      this.$http({
        url: this.$http.adornUrl("/exam/examcategory/tree"),
        method: "post",
        data: this.excludeId,
      }).then(({ data }) => {
        this.menus = data.data;
      });
    },
    batchDelete() {
      let catIds = [];
      let checkedNodes = this.$refs.menuTree.getCheckedNodes();
      for (let i = 0; i < checkedNodes.length; i++) {
        catIds.push(checkedNodes[i].id);
      }
      if (catIds.length === 0) {
        this.$message.error("请先选择分类!");
        return;
      }
      this.$confirm(`是否批量删除【${catIds}】菜单?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/exam/examcategory/delete"),
            method: "post",
            data: this.$http.adornData(catIds, false),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "批量删除成功",
                type: "success",
              });
              this.getMenus();
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch(() => {});
    },
    batchSave() {
      this.$http({
        url: this.$http.adornUrl("/exam/examcategory/update/sort"),
        method: "post",
        data: this.$http.adornData(this.updateNodes, false),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message({
            message: "保存成功",
            type: "success",
          });
          //刷新出新的菜单
          this.getMenus();
          //设置需要默认展开的菜单
          this.expandedKey = this.pCid;
          this.updateNodes = [];
          this.maxLevel = 0;
        }
      });
    },
    handleDrop(draggingNode, dropNode, dropType, ev) {
      this.updateNodes = [];
      // console.log("handleDrop: ", draggingNode, dropNode, dropType);
      // //1、当前节点最新的父节点id
      let pCid = 0;
      let siblings = null;
      if (dropType == "before" || dropType == "after") {
        pCid =
          dropNode.parent.data.id == undefined ? 0 : dropNode.parent.data.id;
        siblings = dropNode.parent.childNodes;
      } else {
        pCid = dropNode.data.id;
        siblings = dropNode.childNodes;
      }
      this.pCid.push(pCid);
      //2、当前拖拽节点的最新顺序，
      for (let i = 0; i < siblings.length; i++) {
        this.updateNodes.push({
          id: siblings[i].data.id,
          sort: i,
        });
      }
      console.log(this.updateNodes);
    },
    allowDrop(draggingNode, dropNode, type) {
      //1、被拖动的当前节点以及所在的父节点总层数不能大于3
      //1）、被拖动的当前节点总层数
      // this.countNodeLevel(draggingNode);
      // console.log(this.maxLevel);
      // console.log(draggingNode.level);
      //当前正在拖动的节点+父节点所在的深度不大于3即可
      // let deep = Math.abs(this.maxLevel - draggingNode.level) + 1;
      // console.log(deep);
      //   this.maxLevel
      //限制只能移动最后一级标签,且不能移动到里面
      // if (this.maxLevel === 0 && type != "inner") {
      //   return true;
      // }
      // return false;
      // if (type == "inner") {
      //   return deep + dropNode.level <= 3;
      // } else {
      //   if (this.maxLevel === 0) {
      //     return true;
      //   }
      //   return deep + dropNode.parent.level <= 3;
      // }
      //只能调整顺序，其他操作一律视为非法拖拽
      if (draggingNode.level === dropNode.level && type != "inner") {
        return true;
      }
      return false;
    },
    countNodeLevel(node) {
      //找到所有子节点，求出最大深度
      if (node.childNodes != null && node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          if (node.childNodes[i].level > this.maxLevel) {
            this.maxLevel = node.childNodes[i].level;
          }
          this.countNodeLevel(node.childNodes[i]);
        }
      }
    },
    edit(data) {
      this.dialogType = "edit";
      this.title = "修改分类";
      this.dialogVisible = true;

      //发送请求获取当前节点最新的数据
      this.$http({
        url: this.$http.adornUrl(`/exam/examcategory/info/${data.id}`),
        method: "get",
      }).then(({ data }) => {
        //请求成功
        if (data && data.code === 0) {
          this.category.id = data.examCategory.id;
          this.category.categoryName = data.examCategory.categoryName;
          this.category.parentId = data.examCategory.parentId;
          this.category.categoryLevel = data.examCategory.categoryLevel;
          this.category.sort = data.examCategory.sort;
          this.category.createTime = data.examCategory.createTime;
          this.category.updateTime = data.examCategory.updateTime;
        }
      });
    },
    append(data) {
      this.dialogType = "add";
      this.title = "添加分类";
      this.dialogVisible = true;
      this.category.parentId = data.id;
      this.category.categoryLevel = data.categoryLevel * 1 + 1;
      this.category.id = null;
      this.category.categoryName = "";
      this.category.sort = data.children ? data.children.length + 1 : 0;
    },
    appendRoot() {
      this.dialogType = "add";
      this.title = "添加分类";
      this.addRootVisible = true;
      this.category.parentId = 0;
      this.category.categoryLevel = 1;
      this.category.id = null;
      this.category.categoryName = "";
      this.category.sort = this.menus.length + 1;
    },
    submitData() {
      if (this.dialogType == "add") {
        this.addCategory();
      }
      if (this.dialogType == "edit") {
        this.editCategory();
      }
    },
    //修改三级分类数据
    editCategory() {
      let { id, categoryName } = this.category;
      this.$http({
        url: this.$http.adornUrl("/exam/examcategory/update"),
        method: "post",
        data: this.$http.adornData({ id, categoryName }, false),
      }).then(({ data }) => {
        this.$message({
          message: "修改成功",
          type: "success",
        });
        //关闭对话框
        this.dialogVisible = false;
        //刷新出新的菜单
        this.getMenus();
        //设置需要默认展开的菜单
        this.expandedKey = [this.category.parentId];
      });
    },
    //添加三级分类
    addCategory() {
      if (!this.category.categoryName) {
        this.$message.error("试卷分类不能为空!");
        return;
      }
      if (
        this.category.categoryName.length < 2 ||
        this.category.categoryName.length > 6
      ) {
        this.$message.error("试卷分类长度必须在 2 到 6 之间!");
        return;
      }
      this.$http({
        url: this.$http.adornUrl("/exam/examcategory/save"),
        method: "post",
        data: this.$http.adornData(this.category, false),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message({
            message: "保存成功",
            type: "success",
          });
          //关闭对话框
          this.dialogVisible = false;
          this.addRootVisible = false;
          //刷新出新的菜单
          this.getMenus();
          //设置需要默认展开的菜单
          this.expandedKey = [this.category.parentId];
        } else {
          this.$message.error(data.msg);
        }
      });
    },
    remove(node, data) {
      let ids = [data.id];
      this.$confirm(`是否删除【${data.categoryName}】菜单?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/exam/examcategory/delete"),
            method: "post",
            data: this.$http.adornData(ids, false),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "删除成功",
                type: "success",
              });
              //刷新出新的菜单
              this.getMenus();
              //设置需要默认展开的菜单
              this.expandedKey = [node.parent.data.id];
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch(() => {});
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getMenus();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style scoped>
</style>